import { Component, OnInit, AfterViewInit } from '@angular/core';

import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Router } from '@angular/router';
import { ReportUrls } from '../../comm/report.urls.conf';
import { Target } from '../../model/report/target';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { MachineFault } from '../../model/report/machine-fault';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';

declare const $: any;
import * as Enumerable from 'linq';
import { CommService } from '../../comm/comm.service';

@Component({
    selector: 'app-report-mfl',
    templateUrl: './mfl.component.html',
    styleUrls: ['./mfl.component.css'],
})

export class MFLineComponent implements OnInit, AfterViewInit {
    title = '整线故障分析';

    showloading = true;
    public type: number;
    public lineMtbf: string;
    public lineMttr: string;
    public lineFT: string;
    public mflList: MachineFault[];
    public mflGroupList: MachineFault[];
    public chartMttrOption: any;
    public chartMtbfOption: any;
    public chartFaultTimeOption: any;
    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];

    public subAareSelected: any;
    public filterValue = 1;
    public shiftSelected: any;
    public equipmentSelected: TVResource[] = [];
    /**目标值设置 */
    public yearItems: string[] = [];
    public yearMonthSelected: string;
    public yearWeekSelected: string;
    public targetItems: Target[];
    public weekTargetItems: Target[];
    public monthTargetItems: Target[];

    constructor(private commServices: CommService,
        public router: Router) {
    }
    // tslint:disable-next-line:member-ordering
    typeList: any = [
        { id: 1, name: '日' },
        { id: 2, name: '周' },
        { id: 3, name: '月' }
    ];

    ngOnInit() {
        this.type = 1;
        this.commServices.initDatePicker3($('#DateTimeRange'), 'YYYY-MM-DD');
        this.initYearValue();
        this.onYearChange('day', 1);
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAareSelected = this.subAreaItems[0];
    }

    /**
     * 获取TimeRange的值
     * @param id id
     */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }
    ngAfterViewInit() {
    }

    onYearChange(year: string, targetType: number) {
        if (year !== '') {
            const target: Target = new Target();
            target.targetType = targetType;
            target.module = 'MachineFault';
            target.year = year;
            this.commServices
                .getList(target, ReportUrls.TargetUrl)
                .subscribe(model => {
                    if (model.resultCode === 200) {
                        if (targetType === 2) {
                            this.weekTargetItems = model.data;
                        } else if (targetType === 3) {
                            this.monthTargetItems = model.data;
                        } else {
                            this.targetItems = model.data;
                        }
                    } else {
                        this.commServices.showNotification('获取数据失败,' + model.resultMessage, 'warning');
                    }
                });
        }
    }

    /**获取表格数据*/
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.reportType = this.type;
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.filterValue = this.filterValue;
        this.commServices
            .getList(queryModel, ReportUrls.MFLineUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.mflList = model.data;
                    this.getGroupData();
                    this.showCharts();
                } else {
                    this.commServices.showNotification('获取数据失败,' + model.resultMessage, 'warning');
                }
            });
    }

    getGroupData(): void {
        this.mflGroupList = Enumerable.from(this.mflList).orderBy(u => u.reportType).groupBy(u => u.reportType).select(u => {
            const temp = new MachineFault();
            let tworkTime = u.groupBy(k => k.resource).select(k => {
                const obj = new MachineFault();
                obj.tworkTime = k.sum(item => item.tworkTime);
                return obj;
            }).max(k => k.tworkTime);
            temp.subArea = u.first().subArea;
            temp.type = this.type === 1 ? '日' : this.type === 2 ? '周' : '月';
            temp.reportType = u.first().reportType;
            temp.targetMttr = u.first().targetMttr;
            temp.targetMcbf = u.first().targetMcbf;
            temp.targetMtbf = u.first().targetMtbf;
            temp.targetFaultRate = u.first().targetFaultRate;
            temp.reportFormat = u.orderBy(e => e.reportFormat).first().reportFormat;
            temp.tfaultTime = Number.parseFloat(u.sum(item => item.tfaultTime * item.weight).toFixed(2));
            if(temp.tfaultTime === undefined){
                temp.tfaultTime = 0;
            }
            temp.tfaultCount = u.sum(item => item.tfaultCount);
            //temp.tworkTime = Number.parseFloat(u.sum(item => item.tworkTime * item.uptime).toFixed(0));
            temp.mttr = Number.parseFloat((temp.tfaultTime / (temp.tfaultCount === 0 ? 1 : temp.tfaultCount)).toFixed(2));
            //（实际的生产时间汇总-故障时间汇总）/故障次数 
            // temp.mtbf = Number.parseFloat(
            //     ((temp.tworkTime - temp.tfaultTime) / (temp.tfaultCount === 0 ? 1 : temp.tfaultCount)).toFixed(2));

            //（实际的生产时间-故障时间汇总）/故障次数 变更时间20210322
            if (tworkTime < temp.tfaultTime) {
                temp.mtbf = 0;
            } else {
                temp.mtbf = Number.parseFloat(
                    ((tworkTime - temp.tfaultTime) / (temp.tfaultCount === 0 ? 1 : temp.tfaultCount)).toFixed(2));
            }
            if (tworkTime === 0 || tworkTime === undefined) {
                tworkTime = 1;
                if (temp.tfaultTime > 0) {
                    tworkTime = temp.tfaultTime;
                }
            }
            temp.tfaultRate = Number.parseFloat(((temp.tfaultTime / tworkTime) * 100).toFixed(2));
            temp.tworkTime = tworkTime;
            return temp;
        }).toArray();
    }
    /**展示报表图表*/
    showCharts(): void {
        const xData = new Array();
        const yDataMttr = new Array();
        const yDataMtbf = new Array();
        const yDataFaultTime = new Array();
        const yMttr = new Array();
        const yMtbf = new Array();
        const yFt = new Array();

        const yMttrTargetData = new Array();
        const yMtbfTargetData = new Array();
        const yFaultTimeTargetData = new Array();

        this.mflGroupList.forEach(e => {
            const station = e.reportFormat;
            xData.push(station);
            yMttr.push(e.mttr.toFixed(2));
            yMtbf.push(e.mtbf.toFixed(2));
            yFt.push(e.tfaultRate.toFixed(2));
            yMttrTargetData.push(e.targetMttr.toFixed(2));
            yMtbfTargetData.push(e.targetMtbf.toFixed(2));
            yFaultTimeTargetData.push(e.targetFaultRate.toFixed(2));
        });
        const yBean = {
            name: 'MTTR',
            type: 'bar',
            data: yMttr
        };
        const yBean1 = {
            name: 'MTBF',
            type: 'bar',
            data: yMtbf
        };
        const yBeanFT = {
            name: '故障率',
            type: 'bar',
            data: yFt
        };
        yDataMttr.push(yBean);
        yDataMtbf.push(yBean1);
        yDataFaultTime.push(yBeanFT);
        const legendMttr = ['MTTR', '目标值'];
        const legendMtbf = ['MTBF', '目标值'];
        const legendFaultTime = ['故障率', '目标值'];
        this.chartMttrOption = ChartOptionCreater.createChartsOption('', '', '', '', legendMttr, xData, yDataMttr, yMttrTargetData); // MTTR
        this.chartMtbfOption = ChartOptionCreater.createChartsOption('', '', '', '', legendMtbf, xData, yDataMtbf, yMtbfTargetData); // MTBF
        this.chartFaultTimeOption = ChartOptionCreater.createChartsOption('', '', '%', '', legendFaultTime,
            xData, yDataFaultTime, yFaultTimeTargetData); // 故障率

    }

    /**ECharts图表相关*/
    chartsMap = new Map<number, any>();
    onChartInit(index: number, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));

        echartsIntance.on('click', (params: any) => {
            const time: string = params.name;
            let startTime, endTime;
            if (this.type === 1) {
                const year = time.slice(0, 4).trim();
                const month = time.slice(4, 6).trim();
                const day = time.slice(6, 8).trim();
                startTime = year + '-' + month + '-' + day;
                const date = new Date(year + '/' + month + '/' + day);
                endTime = this.getLocalTime(date, 1);
            } else if (this.type === 2) {
                const year = time.slice(0, 4).trim();
                const month = time.slice(4, 6).trim();
                const day = time.slice(6, 8).trim();
                startTime = year + '-' + month + '-' + day;
                const date = new Date(year + '/' + month + '/' + day);
                endTime = this.getLocalTime(date, 6);
            } else {
                let year = Number.parseInt(time.slice(0, 4));
                let month = time.slice(4, 6);
                startTime = year + '-' + month + '-01';
                if (Number.parseInt(month) + 1 > 12) {
                    year += 1;
                    month = '1';
                } else {
                    month = (Number.parseInt(month) + 1) + '';
                }
                if (Number.parseInt(month) < 10) { month = '0' + month; }
                endTime = year + '-' + month + '-01';
            }

            this.gotoDetail(startTime + ' - ' + endTime.trim());
        });
    }

    gotoDetail(time: string): void {
        const p = {
            'time': time,
            'subAreas': this.subAareSelected.subArea,
            'shift': JSON.stringify(this.shiftSelected),
            'filterValue': this.filterValue
        };
        this.router.navigate(['/ptpmc/report/mf'], {
            queryParams: p
        });
    }

    getLocalTime(date: Date, addNum: number) {
        let year, month, day, thatDay;
        thatDay = new Date(date.getTime() + addNum * (24 * 60 * 60 * 1000));
        year = thatDay.getFullYear();
        month = thatDay.getMonth() + 1;
        day = thatDay.getDate();
        if (month < 10) { month = '0' + month; }
        if (day < 10) { day = '0' + day; }
        thatDay = year + '-' + month + '-' + day;
        return thatDay;
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }

    selectedCompareIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex + 3).resize();
    }
    /**初始化设置的图表目标值 */
    public initYearValue(): void {
        this.commServices.getList(null, ReportUrls.TargetYearUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.yearItems = model.data;
                    const dt: Date = new Date();
                    this.yearMonthSelected = dt.getFullYear().toString();
                    this.yearWeekSelected = dt.getFullYear().toString();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    public updateTargetList: Target[] = [];
    updateTarget(e) {
        let index: number = this.updateTargetList.findIndex(u => u.id === e.key.id)
        if (index !== -1) {
            this.updateTargetList[index] = e.key;
        } else {
            this.updateTargetList.push(e.key)
        }
    }
    saveTargetChange() {
        this.commServices.update(this.updateTargetList, ReportUrls.TargetUpdateUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.updateTargetList = [];
                    this.commServices.showNotification('更新成功', 'success');
                    this.getReportData();
                } else {
                    this.commServices.showNotification('更新数据失败,' + model.resultMessage, 'warning');
                }
            });
    }
    /**对页面数据进行导出 */
    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();
        queryModelArray.push('查询类型:' + (this.type === 1 ? '日' : this.type === 2 ? '周' : '月'));
        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.subArea);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        queryModelArray.push('过滤值:' + this.filterValue + '分钟');
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
        });
        this.commServices.exportPdf({ reportTitle: this.title, charts: files, queryModel: queryModelArray });
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
